<template>
  <UserLayout :active-index="activeIndex" :active-menu="activeMenu">
    <div class="chat-content">
      <!-- 页面标题 -->
      <div class="page-header">
        <h2>聊天</h2>
        <el-button @click="goBack" icon="ArrowLeft">返回消息中心</el-button>
      </div>

      <!-- 聊天区域 -->
      <div class="chat-area">
          <!-- 聊天头部 -->
          <div class="chat-header">
            <div class="header-left">
              <el-button @click="goBack" icon="ArrowLeft">返回</el-button>
              <div class="user-info">
                <el-avatar :size="40" :src="chatUser.avatar" />
                <div class="user-details">
                  <h3>{{ chatUser.name }}</h3>
                  <p :class="['status', { online: chatUser.online }]">
                    {{ chatUser.online ? '在线' : '离线' }}
                  </p>
                </div>
              </div>
            </div>
            <div class="header-right">
              <el-button icon="More" @click="showUserDetails">用户详情</el-button>
            </div>
          </div>

          <!-- 消息区域 -->
          <div class="chat-messages" ref="messagesContainer">
            <!-- 调试信息已移除 -->

            <div class="messages-list">
              <div v-if="messages.length === 0" class="no-messages">
                <p>暂无消息记录</p>
                <p style="font-size: 12px; color: #999;">
                  {{ loading ? '正在加载消息...' : '开始聊天吧！' }}
                </p>
              </div>

              <div
                  v-for="message in messages"
                  :key="message.id || message.messageId"
                  :class="['message-item', message.sender === 'me' ? 'sent' : 'received']"
              >
                <div class="message-content">
                  <div class="message-text">{{ message.content || message.text }}</div>
                  <div class="message-time">{{ formatTime(message.sendTime || message.time) }}</div>
                </div>
              </div>
            </div>
          </div>

          <!-- 输入区域 -->
          <div class="chat-input">
            <div class="input-tools">
              <el-button icon="Picture" circle size="small" @click="selectImage"></el-button>
              <el-button icon="Folder" circle size="small" @click="selectFile"></el-button>
            </div>
            <el-input
                v-model="newMessage"
                type="textarea"
                :rows="3"
                placeholder="输入消息..."
                @keydown.enter.exact.prevent="sendMessage"
                @keydown.enter.shift.exact.prevent="newMessage += '\n'"
            />
            <div class="input-actions">
              <el-button
                  type="primary"
                  @click="sendMessage"
                  :disabled="!newMessage.trim()"
                  :loading="sending"
              >
                发送
              </el-button>
            </div>
          </div>
        </div>
      </div>
  </UserLayout>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, nextTick, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import UserLayout from '@/components/layout/UserLayout.vue'
import { ArrowLeft, More, Picture, Folder } from '@element-plus/icons-vue'
import { getSessionMessages, sendChatMessage } from '@/utils/apiService'
import { getUserInfo } from '@/utils/auth'
import chatWebSocket from '@/utils/websocket'

const route = useRoute()
const router = useRouter()
const activeMenu = ref('messages')
const activeIndex = ref('4')
const newMessage = ref('')
const sending = ref(false)
const messagesContainer = ref(null)
const loading = ref(false)
const currentUser = ref(null)

// 从路由参数或查询参数获取会话ID
const sessionId = computed(() => {
  // 优先从路由参数获取，如果没有则从查询参数获取
  return route.params.id || route.query.sessionId
})

// 聊天对象信息
const chatUser = ref({
  id: null,
  name: '加载中...',
  avatar: '',
  online: false
})

// 消息列表
const messages = ref([])

// WebSocket连接状态
const wsConnected = ref(false)

// 格式化时间
const formatTime = (time) => {
  if (!time) return new Date().toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })

  // 如果是ISO格式的时间字符串，转换为Date对象
  if (typeof time === 'string' && time.includes('T')) {
    return new Date(time).toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
  }

  // 如果已经是格式化的时间字符串，直接返回
  return time
}

// 返回上一页
const goBack = () => {
  router.push('/message')
}

// 显示用户详情
const showUserDetails = () => {
  ElMessage.info('查看用户详情')
}

// 选择图片
const selectImage = () => {
  ElMessage.info('选择图片功能')
}

// 选择文件
const selectFile = () => {
  ElMessage.info('选择文件功能')
}

// 发送消息
const sendMessage = async () => {
  if (!newMessage.value.trim()) return

  const messageText = newMessage.value.trim()
  const tempMessageId = Date.now()
  sending.value = true

  try {
    // 先添加到本地消息列表（乐观更新）
    const tempMessage = {
      id: tempMessageId,
      senderId: currentUser.value?.id,
      content: messageText,
      sendTime: new Date().toISOString(),
      isRead: 1,
      sender: 'me'
    }

    messages.value.push(tempMessage)

    // 重新排序消息列表
    messages.value.sort((a, b) => {
      const timeA = new Date(a.sendTime || a.time || 0).getTime()
      const timeB = new Date(b.sendTime || b.time || 0).getTime()
      return timeA - timeB
    })

    newMessage.value = ''
    scrollToBottom()

    // 通过WebSocket发送消息
    if (chatWebSocket.isConnected()) {
      chatWebSocket.sendMessage({
        receiverId: chatUser.value.id,
        content: messageText,
        type: 1
      })
    } else {
      // 如果WebSocket未连接，使用REST API
      const response = await sendChatMessage({
        receiverId: chatUser.value.id,
        content: messageText,
        type: 1
      })

      console.log('🔍 发送消息响应:', response)

      const responseData = response.data
      if (!(responseData.code === 200 || responseData.code === '200')) {
        throw new Error(responseData.message || '发送失败')
      }
    }

    ElMessage.success('消息发送成功')
  } catch (error) {
    console.error('发送消息失败:', error)
    ElMessage.error('发送消息失败，请重试')

    // 移除失败的消息
    messages.value = messages.value.filter(msg => msg.id !== tempMessageId)
  } finally {
    sending.value = false
  }
}

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
    }
  })
}

// 加载会话消息
const loadMessages = async () => {
  if (!sessionId.value) {
    console.log('❌ 无会话ID，无法加载消息')
    return
  }

  console.log('🔍 开始加载消息，会话ID:', sessionId.value)
  loading.value = true

  try {
    const response = await getSessionMessages(sessionId.value, { page: 1, size: 50 })

    console.log('🔍 加载消息响应:', response)

    // 响应拦截器返回完整的response对象，实际数据在response.data中
    const responseData = response.data

    if (responseData.code === 200 || responseData.code === '200') {
      console.log('✅ 原始响应数据结构:', responseData)

      // 检查不同可能的数据结构
      const messageList = responseData.data?.messages || responseData.data?.list || responseData.data || []
      console.log('✅ 提取的消息列表:', messageList)
      console.log('✅ 消息列表长度:', messageList.length)
      console.log('✅ 当前用户ID:', currentUser.value?.id)

      if (messageList.length > 0) {
        console.log('✅ 第一条消息示例:', messageList[0])
      }

      messages.value = messageList.map(msg => {
        const processedMsg = {
          ...msg,
          id: msg.messageId || msg.id,
          sender: msg.senderId === currentUser.value?.id ? 'me' : 'them'
        }
        return processedMsg
      }).sort((a, b) => {
        // 按时间正序排序（最早的消息在上面）
        const timeA = new Date(a.sendTime || a.time || 0).getTime()
        const timeB = new Date(b.sendTime || b.time || 0).getTime()
        return timeA - timeB
      })

      // 消息已按时间正序排序
      scrollToBottom()
    } else {
      console.log('❌ 加载消息失败:', responseData)
      ElMessage.error('加载消息失败: ' + (responseData.message || '未知错误'))
    }
  } catch (error) {
    console.error('❌ 加载消息异常:', error)
    ElMessage.error('加载消息失败')
  } finally {
    loading.value = false
  }
}

// 初始化WebSocket连接
const initWebSocket = async () => {
  try {
    await chatWebSocket.connect()
    wsConnected.value = true

    // 添加消息处理器
    chatWebSocket.addMessageHandler('chat-view', (message) => {
      // 只处理当前会话的消息
      if (message.sessionId === sessionId.value) {
        const newMessage = {
          ...message,
          id: message.messageId || message.id,
          sender: message.senderId === currentUser.value?.id ? 'me' : 'them'
        }

        // 添加新消息并重新排序
        messages.value.push(newMessage)
        messages.value.sort((a, b) => {
          const timeA = new Date(a.sendTime || a.time || 0).getTime()
          const timeB = new Date(b.sendTime || b.time || 0).getTime()
          return timeA - timeB
        })

        scrollToBottom()
      }
    })

    // 添加连接状态处理器
    chatWebSocket.addConnectionHandler((connected) => {
      wsConnected.value = connected
    })

  } catch (error) {
    console.error('WebSocket连接失败:', error)
    wsConnected.value = false
  }
}

// 初始化用户信息
const initUserInfo = () => {
  currentUser.value = getUserInfo()
  if (!currentUser.value) {
    ElMessage.error('用户未登录')
    router.push('/login')
    return
  }
}

// 初始化聊天信息
const initChatInfo = () => {
  // 获取当前用户信息
  currentUser.value = getUserInfo()
  if (!currentUser.value) {
    ElMessage.error('用户未登录')
    router.push('/login')
    return false
  }

  // 从路由参数获取聊天信息
  const { userId, userName, houseId, sessionId: routeSessionId } = route.query

  console.log('🔍 聊天路由参数:', { userId, userName, houseId, sessionId: routeSessionId })

  if (!userId) {
    ElMessage.error('缺少聊天对象信息')
    router.go(-1)
    return false
  }

  // 设置聊天用户信息
  chatUser.value = {
    id: parseInt(userId),
    name: userName || '用户',
    avatar: '',
    online: false
  }

  // 会话ID已经通过计算属性从路由参数获取，无需手动设置

  // 如果有房源信息，设置房源信息
  if (houseId) {
    // 这里可以调用API获取房源详情，暂时使用简单信息
    // TODO: 调用API获取房源详情
  }

  return true
}

// 页面加载时初始化
onMounted(async () => {
  console.log('🔍 聊天页面开始初始化')
  console.log('🔍 路由信息:', { params: route.params, query: route.query })

  // 初始化聊天信息
  if (!initChatInfo()) {
    console.log('❌ 聊天信息初始化失败')
    return
  }

  console.log('✅ 聊天信息初始化成功')
  console.log('🔍 当前会话ID:', sessionId.value)
  console.log('🔍 当前用户:', currentUser.value)
  console.log('🔍 聊天对象:', chatUser.value)

  // 初始化WebSocket连接
  await initWebSocket()

  // 如果有会话ID，加载消息历史
  if (sessionId.value) {
    console.log('🔍 准备加载消息历史')
    await loadMessages()
  } else {
    console.log('❌ 没有会话ID，跳过消息加载')
  }

  // 滚动到底部
  scrollToBottom()
})

// 页面卸载前清理
onBeforeUnmount(() => {
  // 移除消息处理器
  chatWebSocket.removeMessageHandler('chat-view')

  // 断开WebSocket连接
  chatWebSocket.disconnect()
})
</script>

<style scoped>
.chat-content {
  padding: 20px;
  height: calc(100vh - 120px);
  display: flex;
  flex-direction: column;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  color: white;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
}

.page-header h2 {
  color: white;
  margin: 0;
  font-size: 24px;
  font-weight: 600;
}

.page-header .el-button {
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: white;
  backdrop-filter: blur(10px);
}

.page-header .el-button:hover {
  background: rgba(255, 255, 255, 0.3);
  border-color: rgba(255, 255, 255, 0.5);
}

.chat-area {
  flex: 1;
  background: white;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  display: flex;
  flex-direction: column;
  backdrop-filter: blur(20px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

/* 聊天样式 */





.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 25px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.user-details h3 {
  margin: 0;
  font-size: 18px;
  color: #2c3e50;
}

.user-details p {
  margin: 5px 0 0;
  font-size: 14px;
  color: #7f8c8d;
}

.user-details .status.online {
  color: #50E3C2;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background: linear-gradient(180deg, #f8f9fa 0%, #e9ecef 100%);
  scrollbar-width: thin;
  scrollbar-color: #c1c1c1 transparent;
}

.chat-messages::-webkit-scrollbar {
  width: 6px;
}

.chat-messages::-webkit-scrollbar-track {
  background: transparent;
}

.chat-messages::-webkit-scrollbar-thumb {
  background-color: #c1c1c1;
  border-radius: 3px;
}

.messages-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.message-item {
  display: flex;
  max-width: 80%;
}

.message-item.sent {
  align-self: flex-end;
  flex-direction: row-reverse;
}

.message-item.received {
  align-self: flex-start;
}

.message-content {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.message-item.sent .message-content {
  align-items: flex-end;
}

.message-item.received .message-content {
  align-items: flex-start;
}

.message-text {
  padding: 14px 18px;
  border-radius: 20px;
  font-size: 14px;
  line-height: 1.5;
  word-wrap: break-word;
  max-width: 100%;
  position: relative;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.message-item.sent .message-text {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-bottom-right-radius: 6px;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
}

.message-item.received .message-text {
  background: white;
  color: #2c3e50;
  border-bottom-left-radius: 6px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  border: 1px solid rgba(0, 0, 0, 0.05);
}

.message-time {
  font-size: 12px;
  color: #7f8c8d;
}

.chat-input {
  display: flex;
  flex-direction: column;
  gap: 12px;
  padding: 20px 25px;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border-top: 1px solid rgba(0, 0, 0, 0.05);
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
}

.input-tools {
  display: flex;
  gap: 12px;
}

.input-tools .el-button {
  border-radius: 8px;
  border: 1px solid rgba(0, 0, 0, 0.1);
  background: white;
  color: #666;
  transition: all 0.3s ease;
}

.input-tools .el-button:hover {
  background: #f8f9fa;
  border-color: #667eea;
  color: #667eea;
}

.input-actions {
  display: flex;
  justify-content: flex-end;
}

.input-actions .el-button--primary {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  border-radius: 10px;
  padding: 10px 20px;
  font-weight: 500;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
  transition: all 0.3s ease;
}

.input-actions .el-button--primary:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
}

/* 输入框美化 */
:deep(.el-textarea__inner) {
  border-radius: 12px;
  border: 1px solid rgba(0, 0, 0, 0.1);
  background: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  resize: none;
}

:deep(.el-textarea__inner:focus) {
  border-color: #667eea;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.2);
}

@media (max-width: 992px) {
  .sidebar {
    width: 80px;
  }

  .app-title,
  .el-menu-item span,
  .el-sub-menu__title span {
    display: none;
  }

  .chat-header {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }

  .header-left,
  .header-right {
    width: 100%;
  }

  .message-item {
    max-width: 90%;
  }
}
</style>
